module main(clk,reset,instru,sel,seg,PC);
input clk;
input reset;    //低电平清零
input [15:0]instru;  //存储器返回的指令

output reg [2:0]sel;
output reg [7:0]seg;
output reg [7:0]PC;
reg [3:0]OP; //操作符
reg [7:0]R1,R2,R3,R4,RX,RY,RZ;//寄存器
reg [1:0]x,y,z;  //操作数
reg [1:0]state; //状态
reg [3:0]data;
reg div_clk; //分频后的时钟频率
reg [15:0] count; //分频计数

//分频
always @(posedge clk)
begin 
	if(count == 500)
	begin 
		count = 0;
		div_clk = ~div_clk;
	end 
	else 
		count = count + 1;
end

//状态机 时钟周期
always@(negedge clk or negedge reset)
begin
	if(~reset) //清零信号
		state=0;
	else
	begin
		if(OP==8 && state==2)
			state=0;
		else
			state=state+1;
	end
end

//状态切换操作
always@(posedge clk or negedge reset)
begin
	if(~reset)
	begin
		R1=8'HDC;
		R2=8'H9A;
		R3=8'HB6;
		R4=8'H57;
		PC=0; 
	end 
	else
	begin 
	if(PC==3) PC=0; 
		case(state)
			0:begin //状态0 取指令
				 OP=instru[15:12];
				 x=instru[11:10];
				 y=instru[9:8];
				 z=instru[7:6];
				 PC=PC+1;
			  end
			1:begin //状态1 翻译指令 获取RX
			    case(x)
					0:RX=R1;
					1:RX=R2;
					2:RX=R3;
					3:RX=R4;
				 endcase
			  end 
			2:begin //状态2 翻译指令 获取RY或进行运算
				 if(OP==7)
				 begin 
						case(y)
						0:RY=R1;
						1:RY=R2;
						2:RY=R3;
						3:RY=R4;
						endcase
				 end 
				 else if(OP==8)
				 begin 
						RY=RX>>1;
						case(y)
						0:R1=RY;
						1:R2=RY;
						2:R3=RY;
						3:R4=RY;
						endcase
				 end
			  end
			3:begin //状态3 翻译指令 运算
				 if(OP==7)
				 begin 
					RZ=RX^RY;
					case(z)
						0:R1=RZ;
						1:R2=RZ;
						2:R3=RZ;
						3:R4=RZ;
					endcase
				 end
			  end 
		endcase
	end
	
end

//数码管输出
always @(posedge clk)
begin
	sel=sel+1;
	case(sel)
		3'd0: data=R1[7:4]; 
		3'd1: data=R1[3:0]; 
		3'd2: data=R2[7:4];
		3'd3: data=R2[3:0];
		3'd4: data=R3[7:4]; 
		3'd5: data=R3[3:0]; 
		3'd6: data=R4[7:4];
		3'd7: data=R4[3:0];
	endcase
	case(data)
			4'h0: seg=8'h3F;
			4'h1: seg=8'h06;
			4'h2: seg=8'h5B;
			4'h3: seg=8'h4F;
			4'h4: seg=8'h66;
			4'h5: seg=8'h6D;
			4'h6: seg=8'h7D;
			4'h7: seg=8'h07;
			4'h8: seg=8'h7F;
			4'h9: seg=8'h6F;
			4'hA: seg=8'h77;
			4'hB: seg=8'h7C;
			4'hC: seg=8'h39;
			4'hD: seg=8'h5E;
			4'hE: seg=8'h79;
			4'hF: seg=8'h71;
			default: seg=8'h00;
		endcase
end 

endmodule 